package cn.gailvlun.gll.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatSeekBar;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import cn.gailvlun.gll.net.R;
import cn.gailvlun.gll.util.LogUtil;



public class TextSeekBar extends LinearLayout implements SeekBar.OnSeekBarChangeListener {
    private int mPosition;
    public TextSeekBar(Context context) {
        this(context, null);
    }

    public TextSeekBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TextSeekBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TextSeekBar);
        defaultPosition = ta.getInt(R.styleable.TextSeekBar_defaultPosition, 1);
        ta.recycle();

        setOrientation(VERTICAL);
        View.inflate(getContext(), R.layout.text_seek_bar, this);

        tvTop = findViewById(R.id.tv_top);
        sb = findViewById(R.id.sb);

        sb.setOnSeekBarChangeListener(this);

        getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                getViewTreeObserver().removeOnGlobalLayoutListener(this);
                setPosition(defaultPosition);
            }
        });
    }

    private TextView tvTop;
    private AppCompatSeekBar sb;
    private int defaultPosition;

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        setPosition(progress + 1);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        sb.setProgress(defaultPosition - 1);
    }

    
    private void setPosition(int position) {

        mPosition =position;
        tvTop.setText(position + "天");
        tvTop.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
        int textWidth = tvTop.getMeasuredWidth();
        int [] outLocation = new int[2];
        sb.getLocationInWindow(outLocation);

        LinearLayout.LayoutParams lp = (LayoutParams) sb.getLayoutParams();

        tvTop.setTranslationX(outLocation[0] +
                sb.getThumb().getBounds().left - textWidth / 2);

        LogUtil.d("leftX: " + outLocation[0] + ", leftMargin: " + lp.leftMargin +
                ", thumbRect: " + sb.getThumb().getBounds() + ", textWidth: " + textWidth);
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

    }
    public int getPosition() {
        return mPosition;
    }
}
